package com.cqemme.activitiservice.controller.process;

import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 高亮流程图当前任务控制器
 * 前端代码：      <img src="http://127.0.0.1:90/activity/image?processInstanceId=2501"/>
 */
@ApiIgnore
@Controller
@RequestMapping("/activity")
@Slf4j
public class ControllerDe {

    @Resource
    RepositoryService repositoryService;
    @Resource
    protected RuntimeService runtimeService;
    @Resource
    protected ProcessEngine processEngine;
    @Resource
    HistoryService historyService;

    /**
     * 查看流程图
     */
    @RequestMapping(value = "/image", method = RequestMethod.GET)
    public void image(HttpServletResponse response,
                      @RequestParam String processInstanceId) {
        try {
            InputStream is = getDiagram(processInstanceId);
            if (is == null){
                return;
            }

            response.setContentType("image/png");

            BufferedImage image = ImageIO.read(is);
            OutputStream out = response.getOutputStream();
            ImageIO.write(image, "png", out);

            is.close();
            out.close();
        } catch (Exception ex) {
            log.error("查看流程图失败", ex);
        }
    }


    public InputStream getDiagram(String processInstanceId) {
        //获得流程实例
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
                .processInstanceId(processInstanceId).singleResult();
        String processDefinitionId = StringUtils.EMPTY;
        if (processInstance == null) {
            //查询已经结束的流程实例
            HistoricProcessInstance processInstanceHistory =
                    historyService.createHistoricProcessInstanceQuery()
                            .processInstanceId(processInstanceId).singleResult();
            if (processInstanceHistory == null){
                return null;
            }
            else{
                processDefinitionId = processInstanceHistory.getProcessDefinitionId();
            }
        } else {
            processDefinitionId = processInstance.getProcessDefinitionId();
        }

        //使用宋体
        String fontName = "宋体";
        //获取BPMN模型对象
        BpmnModel model = repositoryService.getBpmnModel(processDefinitionId);
        //获取流程实例当前的节点，需要高亮显示
        List<String> currentActs = Collections.EMPTY_LIST;
        if (processInstance != null){
            currentActs = runtimeService.getActiveActivityIds(processInstance.getId());
        }

        return processEngine.getProcessEngineConfiguration()
                .getProcessDiagramGenerator()
                .generateDiagram(model, "png", currentActs, new ArrayList<String>(),
                        fontName, fontName, fontName, null, 1.0);
    }
//    generateDiagram 方法参数说明
//    bpmnModel：bpmnModel对象
//
//    imageType：生成的图像格式，我用的是png
//
//    highLightedActivities：要高亮显示的活动的节点
//
//    highLightedFlows：高亮显示的连线
//
//    activityFontName：activity字体，默认字体是Arial，如果你的流程图中使用了中文，那么会显示乱码
//
//    labelFontName：label字体，同时
//
//    annotationFontName：annotation字体，同上
//
//    customClassLoader：提供一个自定义类加载器来检索图标图像
//
//    scaleFactor：比例因子，试着改了一下，会改变连线箭头的大小，一般设置为1.0

}